<!-- 广告列表 
    从分页组件传了两个事件过来pageChange
-->
<template>
    <div class="main" @scroll.passive="scrollTop($event)">
        <!-- 广告头部 -->
        <div class="ad-top">
            <el-space wrap :size="10">
                <el-select v-model="searchData.adStatus" placeholder="请选择广告状态" style="width: 10vw;" clearable>
                    <el-option :label="item.name" :value="item.value" v-for="item in adStatusMap" :key="item.value" />
                </el-select>
                <el-select v-model="searchData.adType" placeholder="请选择广告类型" style="width: 10vw;" clearable>
                    <el-option :label="item.name" :value="item.value" v-for="item in adTypeMap" :key="item.value" />
                </el-select>
                <el-button type="primary" :icon="Search" @click="handlrsearch">查找</el-button>
                <el-button type="primary" :icon="Plus" @click="handlrAdd">添加</el-button>
            </el-space>
        </div>
        <!-- 广告列表 -->
        <div class="ad-table">
            <div>
                <el-table :data="tableData" border style="width: 100%;" id="table">
                    <el-table-column prop="id" label="广告ID" align="center" sortable />
                    <el-table-column prop="title" label="广告标题" align="center" />
                    <el-table-column prop="imgUrl" label="广告图片" align="center">
                        <template #default="scope">
                            <template v-if='adTypeMap.find(item=>item.value==scope.row.type)?.picRequire'>
                                <el-popover width="450px" placement="right"
                                    :popper-style="'background-color:'+scope.row.color">
                                    <template #reference>
                                        <el-image style="width: 100px;height: 50px;" :src="scope.row.imgUrl"
                                            fit="contain" />
                                    </template>
                                    <template #default>
                                        <div style="display: flex;justify-content: center;">
                                            <el-image style="width: 400px; height: 100%" :src="scope.row.imgUrl" />
                                        </div>
                                    </template>
                                </el-popover>
                            </template>
                            <template v-else>
                                <el-tag type="info">类型无需图片</el-tag>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="type" label="广告类型" align="center">
                        <template #default="scope">
                            <template v-for="item in adTypeMap">
                                <el-tag v-if="item.value==scope.row.type">{{item.name}}</el-tag>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="广告状态" align="center">
                        <template #default="scope">
                            <el-tag :type="scope.row.status==0?'danger':'success'">{{scope.row.status==0?'冻结':'激活'}}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unionType" label="关联类型" align="center">
                        <template #default="scope">
                            <template v-for="item in adUnionTypeMap">
                                <el-tag v-if="item.value==scope.row.unionType" type='warning'>{{item.name}}</el-tag>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unionValue" label="关联值[ID]" align="center" />
                    <el-table-column prop="gmtCreate" label="创建时间" align="center">
                        <template #default="scope">
                            <template v-if="scope.row.gmtCreate">
                                {{new Date(scope.row.gmtCreate).friendTime(1)}}
                            </template>
                            <template v-else>
                                <span>无</span>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="200">
                        <template #default="scope">
                            <el-button type="primary" @click="handlrEdit(scope.row)">编辑</el-button>
                            <el-button type="danger" @click="handlrDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div>
                <!-- 添加和修改弹出框 -->
                <el-dialog v-model="dialogFormVisible" :title="bool?'创建':'编辑'" :destroy-on-close="true">
                    <el-form ref="ruleFormRef" :model="form" require-asterisk-position="left" class="demo-ruleForm"
                        status-icon :rules="rules">
                        <el-form-item label="广告标题" class="is-required" prop="title">
                            <el-input v-model.trim="form.title" clearable />
                        </el-form-item>
                        <el-form-item label="广告类型" prop="type" class="is-required">
                            <el-select v-model="form.type" style="width: 10vw;" clearable @change="emptyData">
                                <el-option :label="item.name" :value="item.value" v-for="item in adTypeMap"
                                    :key="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="广告图片" class="is-required" prop="imgUrl"
                            v-show="adTypeMap.find(item=>item.value==form.type)?.picRequire" id="upload" ref="upload">
                            <el-upload class="avatar-uploader" :headers="headers" action="/upload/admin"
                                :show-file-list="false" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="广告状态" class="is-required" prop="status">
                            <el-switch v-model="form.status" class="ml-2" :active-value="1" :inactive-value="0"
                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                        </el-form-item>
                        <el-form-item label="关联类型" class="is-required" prop="unionType">
                            <el-select v-model="form.unionType" style="width: 10vw;" clearable
                                @change="form.unionValue=''">
                                <el-option :label="item.name" :value="item.value" v-for="item in adUnionTypeMap"
                                    :key="item.value"
                                    :disabled="form.type=='' ||adTypeMap.find(item=>item.value==form.type)?.unionTypes.findIndex(items=>items==item.value)==-1" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="商品" class="is-required" placeholder="关联至商品" v-if="form.unionType==1"
                            prop="unionValue">
                            <el-cascader :options="options" :props="props" v-model='form.unionValue' />
                        </el-form-item>
                        <el-form-item label="类目" v-if="form.unionType==2" class="is-required" prop="unionValue">
                            <div class="example-block">
                                <el-cascader :options="option" :props="props1" clearable v-model="form.unionValue"
                                    prop="unionValue" />
                            </div>
                        </el-form-item>
                        <el-form-item label="关键字" v-if="form.unionType==3" class="is-required" prop="unionValue">
                            <el-input v-model="form.unionValue" clearable />
                        </el-form-item>
                        <el-form-item label="功能" v-if="form.unionType==4" class="is-required" prop="unionValue">
                            <el-select v-model="form.unionValue" clearable>
                                <el-option :label="item.name" :value="item.value" v-for="item in functionPages" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormVisible=false">取消</el-button>
                            <el-button type="primary" @click="AddDetermine(ruleFormRef)">确定</el-button>
                        </span>
                    </template>
                </el-dialog>
            </div>
        </div>
        <!-- 分页组件 -->
        <div>
            <Paging v-bind="pagingDatas" @page-change="pageChange"></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main" :visibility-height="0" v-if="bool" />
    </div>
</template>
<script  setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue'
import { Search, Plus, } from '@element-plus/icons-vue'
import { ClassPagination } from "#/index";
import { ElMessage, ElMessageBox } from 'element-plus'
import Paging from "@/components/paging/Paging.vue";
import { get, post } from "@/utils/request";
import type { FormInstance } from 'element-plus'
import Cookie from "js-cookie";
import type { UploadProps } from 'element-plus'
import { theColorFn } from "@/utils/theColot";
import "@/utils/dataFriend"
const ruleFormRef = ref<FormInstance>()
let dialogFormVisible = ref(false) //控制修改框是否可见
let main = ref()  //滚动组件对象的引用
let upload = ref()
let bool = ref(true)  //用来判断滚动组件的显示隐藏
let rollHeight = ref(0)  //滚动距离
let tableData: TypeAdList[] = reactive([]) //广告列表数据
//分页数据
let pagingDatas = reactive(new ClassPagination())

const headers = reactive({ //获取请求头
    AdminToken: Cookie.get('token')
})
const searchData = reactive({
    adStatus: undefined,//广告状态
    adType: undefined,//广告类型
})

let form: TypeAdList = reactive({
    id: '',
    title: '', //广告标题
    type: '', //广告类型
    imgUrl: '', //广告图片
    status: 1, //广告状态
    unionType: '', //关联类型
    unionValue: '', //商品
    color: '' //颜色
})
let newsearchData = { ...searchData }
//广告状态
const adStatusMap = reactive([{ value: 0, name: '冻结' }, { value: 1, name: '激活' }])
//广告类型
const adTypeMap = reactive([
    { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: '轮播' },
    { value: 2, unionTypes: [2], picRequire: true, name: '分类精选' },
    { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: '横幅' },
    { value: 4, unionTypes: [1, 2, 3, 4], picRequire: true, name: '首页轮播下5按钮' },
    { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: '公告' },
    { value: 9, unionTypes: [1], picRequire: false, name: '商品推荐' }
])
//关联类型
const adUnionTypeMap = reactive([
    { value: 1, name: '商品' },
    { value: 2, name: '类目' },
    { value: 3, name: '关键字' },
    { value: 4, name: '功能页面' }
])

//弹出框验证
const validateTitle = (rule: object, value: string, callback: Function) => {
    if ('' === value) {
        return callback(new Error('内容不能为空'))
    } else {
        callback()
    }
}
//失焦触发验证
const rules = reactive({
    title: [{ validator: validateTitle, trigger: 'blur' }],
    type: [{ validator: validateTitle, trigger: ['blur', 'change'] }],
    status: [{ validator: validateTitle, trigger: 'blur' }],
    unionType: [{ validator: validateTitle, trigger: ['blur', 'change'] }],
    unionValue: [{ validator: validateTitle, trigger: ['blur', 'change'] }]
})
//功能
const functionPages = reactive([
    { value: "/pages/product/groupshop", name: "团购列表" },
    { value: "/pages/coupon/list", name: "优惠卷列表" }
])
const options: TypeAdOptions[] = reactive([]) //商品列表
const option: TypeOptions[] = reactive([])//类目列表
const props = {
    emitPath: false,
    value: 'id',
    label: 'label',
    children: 'children',
}
const props1 = {
    emitPath: false,
    checkStrictly: true,
    value: 'id',
    label: "title",
    children: "childrenList"
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    if (200 == response.errno) {
        form.imgUrl = response.url // 得到上传图片成功的路径
        theColorFn(form.imgUrl, (callback: string) => {
            form.color = callback
        }) // 计算得到图片平均色
        lodeAdList()
    }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg' && rawFile.type !== 'image/png') {
        ElMessage.error('请选择jpeg、jpg、png格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片最多只能2MB!')
        return false
    }
    return true
}
//更改广告类型清空下面的数据
function emptyData() {
    form.unionType = ''
    if (bool.value == true) {
        upload.value.$el.style.backgroundColor = 'transparent'
        form.imgUrl = ''
    }
}

//加载广告列表
function lodeAdList() {
    let data = {
        _gp: 'admin.advert',
        _mt: 'list',
        type: newsearchData.adType,
        status: newsearchData.adStatus,
        pageNo: pagingDatas.page,
        limit: pagingDatas.limit
    }
    get(data).then((res) => {
        console.log(res)
        if (200 == res.errno) {
            tableData.length = 0
            pagingDatas.total = res.data.total
            tableData.push(...res.data.items)
        } else {
            tableData.length = 0
            ElMessage.error(res.errmsg)
        }
    })
}

//商品列表
function lodeCommodityTree() {
    if (0 == options.length) {
        post({ _gp: 'admin.product', _mt: 'getSpuBigTree' }).then((res) => {
            console.log(res)
            if (200 == res.errno) {
                options.length = 0
                options.push(...res.data)
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }
}
lodeCommodityTree()
//类目列表
function lodeCategory() {
    if (0 == option.length) {
        let data = {
            _gp: 'admin.category',
            _mt: 'categoryTree',
        }
        get(data).then((res) => {
            console.log(res)
            if (200 == res.errno) {
                option.length = 0
                option.push(...res.data)
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }
}
lodeCategory()
//分页组件每次调用事件
function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    lodeAdList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}


//滚动事件
let scrollTop = (e: Event) => {
    rollHeight.value = Math.floor((e.target as EventTarget).scrollTop)
}
//监听滚动的距离
watch(rollHeight, (val: number) => {
    //    console.log(val);
    bool.value = val > 60
})
//查找
function handlrsearch() {
    Object.assign(newsearchData, searchData)
    lodeAdList()
}
let newForm = { ...form }
//添加
function handlrAdd() {
    bool.value = true
    dialogFormVisible.value = true
    Object.assign(form, newForm)
}

//编辑
function handlrEdit(row: TypeAdList) {
    dialogFormVisible.value = true
    bool.value = false
    Object.assign(form, row)
    if (form.unionType < 3) {
        form.unionValue = Math.ceil(form.unionValue)
    }
    nextTick(() => {
        upload.value.$el.style.backgroundColor = form.color
    })
}
//添加确认
function AddDetermine(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (form.type == 6 || form.type == 9) {
                form.color = ''
                form.imgUrl = ''
            } else if (form.imgUrl == '') {
                ElMessage.error("图片不能为空")
                return
            }
            let data = {
                _gp: 'admin.advert',
                _mt: bool.value == true ? 'create' : 'edit',
                imgUrl: form.imgUrl == '' ? ' ' : form.imgUrl,
                adId: form.id,
                type: form.type,
                unionType: form.unionType,
                title: form.title,
                unionValue: form.unionValue,
                status: form.status,
                color: form.color
            }
            post(data).then((res) => {
                if (200 == res.errno) {
                    ElMessage.success(bool.value == true ? "添加成功" : "修改成功")
                    dialogFormVisible.value = false
                    lodeAdList()
                } else {
                    ElMessage.error(res.errmsg)
                }
            })
        } else {
            console.log('error submit!')
            return false
        }
    })
}
//删除
function handlrDelete(row: TypeAdList) {
    // console.log(row)
    let data = {
        _gp: 'admin.advert',
        _mt: 'delete',
        type: row.type,
        adId: row.id,
    }
    ElMessageBox.confirm(
        '请问是否删除',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
        }
    ).then(() => {
        get(data).then((res) => {
            if (200 == res.errno) {
                ElMessage.success("删除成功")
                lodeAdList()
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    })
        .catch(() => {
            ElMessage.info("取消操作")
        })


}


lodeAdList()
</script>
<style scoped lang="less">
.ad-top {
    margin: 15px 0px;

    .el-input {
        width: 11vw;
    }
}

.ad-table {
    .el-dialog {
        .el-form {
            &::v-deep .el-form-item__label {
                width: 15vw;
            }

            text-align: center;

            .el-form-item__content {
                .el-input {
                    width: 20vw;
                }
            }

            /deep/ .el-cascader {
                width: 10vw;
            }
        }
    }

    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    /deep/ .avatar-uploader .el-upload {
        border: 1px solid var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
}
</style>